//
//  HgViewController.m
//  zuixin
//
//  Created by QJY on 14-8-22.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "HgViewController.h"
#import "NetAccess.h"
#import "MBProgressHUD.h"
#import "Header.h"
#import "DingSh.h"
#import "FMDBManager.h"
#import "LogViewController.h"
#import "AFNetworking.h"
#import "Base64Encry.h"
#import "ZifViewController.h"
@interface HgViewController ()<UITextFieldDelegate,NSURLConnectionDataDelegate>

@end

@implementation HgViewController
{
    UITextField *_field;
    UITextField *_field1;
    UITextField *_field2;
    NSMutableData *_data;
    UIAlertView *_alertView;
    NSInteger _string;
    UIImageView *_imageView;
    MBProgressHUD *pro;
    NSUserDefaults *users;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view removeFromSuperview];
    [pro removeFromSuperview];
    _field.text =nil;
    _field1.text =nil;
    [_field resignFirstResponder];
    [_field1 resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self textfield];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navgationbar.png"] forBarMetrics: UIBarMetricsDefault];
    
    
}
-(void)sleep
{
    UIButton*button=(UIButton*)[self.view viewWithTag:91];
    button.userInteractionEnabled=YES;
}

-(void)btnClick//:(UIButton*)sender
{
    
    
    
    NetAccess *net =[NetAccess sharedNetAccess];
    if(![net haveNet])
    {
        
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        
        
    }
    else
    {
        NSLog(@"111111%@%@",_field.text,_field1.text);
        if (IOS5) {
            if (!(_field.text||_field.text))
            {
                
                _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [_alertView show];
            }
            else{
                [self getShuJu];
            }
        }
        else
        {
            
            if ([_field.text isEqualToString:@""]||[_field1.text isEqualToString:@""])
            {
                
                _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                
                [_alertView show];
                
            }
            else
            {
                [self getShuJu];
            }
        }}
}
-(void)getShuJu
{
    
//    NSString *str=[NSString stringWithFormat:@"http://oemapi2.leehuu.cn/api/Vos/Logon?userName=%@&Password=%@&parent=62634",_field.text,_field1.text];
//    NSLog(@"wohao %@   %@   %@",_field.text,_field1.text, _field2.text);
//    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSMutableURLRequest*request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *html = operation.responseString;//@"{\"retCode\":-1,\"exception\":\"密码错误！\"}";
//        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
//        if (data==nil) {
//            [pro removeFromSuperview];
//            UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"服务不可用，请稍后再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//        }
//        else
//        {
//
    
     pro=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //登录地址
    NSString*urlStr=@"http://oemapi2.leehuu.cn/YXBp/dm9zb2Vt/TG9nb24PQ";
    NSString * parameterStr=[NSString stringWithFormat:@"dXNlck5hbWUPQ=%@&password=%@&parent=2645421&proxyId=2645421",[Base64Encry switchBase64String:_field.text],_field1.text];
    NSLog(@"登录%@",[NSString stringWithFormat:@"%@  %@",urlStr,parameterStr]);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       id dict=[Base64Encry switchUrlString:urlStr switchParameterString:parameterStr];
        self.excString=[dict objectForKey:@"exception"];
        self.retString=[dict objectForKey:@"retCode"];
        if ([dict count]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
               
                 NSString *message = @"登录成功";
                if ([self isBlankString:self.retString]) {
                    [pro removeFromSuperview];
                    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"网络信号不好，请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                }
                else
                {
                    if ([self.retString intValue])
                    {
                        [pro removeFromSuperview];
                        message=self.excString;
                        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        
                        [_alertView show];
                        //return;
                    }
                    else
                        //信息正确
                    {
                        
                        [_field resignFirstResponder];
                        [_field1 resignFirstResponder];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
                        //本地存储
                        
                        //
                        [pro removeFromSuperview];
                        NSMutableArray *_usert =[NSMutableArray array];
                        [_usert removeAllObjects];
                        users =[NSUserDefaults standardUserDefaults];
                        NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
                        [dict setObject:_field.text forKey:@"username"];
                        [dict setObject:_field1.text forKey:@"userword"];
                        //[dict setObject:userId forKey:@"userID"];
                        [_usert addObject:dict];
                        [users setObject:_usert forKey:@"newusers1"];
                        [users synchronize];
                        
                        //            return;
                    }}

            });
        }
    });}
    
    
    
    
    
        // 提示框
    //    //跳转拨号键盘
//    // [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
//}

- (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    return NO;
}

#pragma mark--网络代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *rootDict =[NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    _string =[[rootDict objectForKey:@"retCode"] integerValue];
    if(_string==0)
    {[pro removeFromSuperview];
        NSMutableArray *_usert =[NSMutableArray array];
        [_usert removeAllObjects];
        users =[NSUserDefaults standardUserDefaults];
        NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
        NSString *sdxc =@"123456";
        [dict setObject:_field.text forKey:@"username"];
        [dict setObject:sdxc forKey:@"userword"];
        [_usert addObject:dict];
        [users setObject:_usert forKey:@"newusers1"];
        [users synchronize];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
        return;
    }
    else
    {[pro removeFromSuperview];
        LogViewController *log =[[LogViewController alloc]init];
        [self presentViewController:log animated:YES completion:^{
        }];
        return;
    }
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{[pro removeFromSuperview];
    NSString *message =@"亲！网络不给力啊，稍后再试吧..!";
    _alertView.message = message;
    [_alertView show];
}
-(void)textfield
{
    self.view.backgroundColor =[UIColor whiteColor];
   
    _imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon.png"]];
    _imageView.frame =CGRectMake(100, 70 ,90, 90);
    [self.view addSubview:_imageView];
    
    
    
    _field =[[UITextField alloc]initWithFrame:CGRectMake(20,40+140, 320-40,35)];
    _field.delegate=self;
    _field.backgroundColor =[UIColor whiteColor];
    _field.borderStyle = UITextBorderStyleRoundedRect;
    _field.keyboardType=UIKeyboardTypeNumberPad;
    _field.placeholder = @"手机号码:";
    [self.view addSubview:_field];
    _field1 =[[UITextField alloc]initWithFrame:CGRectMake(20,40+140+45, 320-40,35)];
    _field1.backgroundColor =[UIColor whiteColor];
    _field1.borderStyle = UITextBorderStyleRoundedRect;
    _field1.placeholder = @"密码:";
    _field1.secureTextEntry=YES;
    _field1.keyboardType=UIKeyboardTypeASCIICapable;
    _field1.delegate=self;
    [self.view addSubview:_field1];
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    // btn .frame =CGRectMake(20, _field1.frame.size.height+240, 280, 40);
    btn.frame =CGRectMake(20, _field1.frame.origin.y+_field1.frame.size.height+15, 280, 40);
    NSLog(@"aaaa%f",_field1.frame.origin.y+_field1.frame.size.height+10);
    btn.backgroundColor =[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
    [btn setTitle:@"登录" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.cornerRadius =10;
    btn.tag=91;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    UIButton *btn1 =[UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame =CGRectMake(20, _field1.frame.origin.y+_field1.frame.size.height+15+50, 280, 40);
    NSLog(@"aaaa%f",_field1.frame.origin.y+_field1.frame.size.height+10);
    btn1.backgroundColor =[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
    [btn1 setTitle:@"返回" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn1.layer.cornerRadius =10;
    [btn1 addTarget:self action:@selector(btnClick1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    UIButton *btn2 =[UIButton buttonWithType:UIButtonTypeCustom];
    
    btn2.frame =CGRectMake(80, btn1.frame.origin.y+btn1.frame.size.height+10, 160, 40);
    NSLog(@"aaaa%f",_field1.frame.origin.y+_field1.frame.size.height+10);
    btn2.titleLabel.font=[UIFont systemFontOfSize:14];
    [btn2 setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1] forState:UIControlStateNormal];
    btn2.layer.cornerRadius =10;
    [btn2 addTarget:self action:@selector(btnClick2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    

}
-(void)btnClick1
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)btnClick2
{
    ZifViewController *micro=[[ZifViewController alloc]init];
    micro.phoneString=_field.text;
    micro.block1=^(NSString*str)
    {
        NSLog(@"...ee%@",str);
        _field.text=str;
    };
    [self presentViewController:micro animated:YES completion:nil];
}
-(void)match
{
//    pro = [[MBProgressHUD alloc] initWithView:self.view];
//    pro.labelText = @"正在加载中..";
//    pro.mode = MBProgressHUDModeText;
//    [self.view addSubview:pro];
//    [pro showAnimated:YES whileExecutingBlock:^{
//        //[NSThread sleepForTimeInterval:2.0];
//        [self btnClick];
//    } completionBlock:^{
//        
//    }];
   
    [self btnClick];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_field resignFirstResponder];
    [_field1 resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
//键盘上下移动
-(void)textFieldDidBeginEditing:(UITextField *)textField{   //开始编辑时，整体上移
    //    if (textField.tag==0) {
    //        [self moveView:-20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:-40];
    //    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时，整体下移
    //    if (textField.tag==0) {
    //        [self moveView:20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:40];
    //    }
}
-(void)moveView:(float)move{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y+=move;//view的X轴上移
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
